package com.whzykj.ctrl;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import com.whzykj.common.AmountUtils;
import com.whzykj.common.CommonUtils;
import com.whzykj.common.DateUtil;
import com.whzykj.common.wx.WxConst;
import com.whzykj.common.wx.XMLUtil;
import com.whzykj.model.Account;
import com.whzykj.model.PayLog;
import com.whzykj.model.Userinfo;
import com.whzykj.model.VirtualOrder;

public class WxPayController extends Controller{
	/**
	 * 微信订单支付回调
	 * 支付结果
	 * */
	public void payresult() {
		System.out.print("微信支付回调获取数据开始");
		HttpServletRequest request = getRequest();
		String inputLine;
		//String notityXml = "<xml><appid><![CDATA[wx7d9d3839bcf7a60b]]></appid><attach><![CDATA[1]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[39500]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1397982802]]></mch_id><nonce_str><![CDATA[RfO38rYBIREtjlKUCeU1FqLBzqkmj3Jn]]></nonce_str><openid><![CDATA[ovbm3v1eeZAAcxyBgQAtGY7V1qkA]]></openid><out_trade_no><![CDATA[APP20161101123039594]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[7C2EB306C76A64F44B8F8E812244220D]]></sign><time_end><![CDATA[20161101073517]]></time_end><total_fee>39500</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4002522001201609244763839121]]></transaction_id></xml>";
		String notityXml="";
		try {

			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			System.out.println("xml获取失败：" + e);
		}
		System.out.println("接收到的报文：" + notityXml);
		// 开始解析报文
        Map<String,Object> map = null;
       try {
       	map =XMLUtil.doXMLParse(notityXml);
       	//transaction_id 微信支付订单号
      	String tid = CommonUtils.getMapKeyVal(map, "transaction_id");
       	//out_trade_no商户订单号
       	String out_trade_no =CommonUtils.getMapKeyVal(map, "out_trade_no");
       	//attach  商家数据包 客户端自定义
    	String attach =CommonUtils.getMapKeyVal(map, "attach");
		//String userid = String.valueOf(SysUser.me.userInfo(openid).get("user_id"));
       	//现金支付金额订单现金支付金额，详见
		String amount = CommonUtils.getMapKeyVal(map, "cash_fee");
		/**把分转换成元**/
		String allamount = AmountUtils.changeF2Y(amount);
		
		//time_end 支付完成时间
		String time_end = CommonUtils.getMapKeyVal(map, "time_end");
		//付款银行
		String bank_type = CommonUtils.getMapKeyVal(map, "bank_type");
		//先完成充值流程
		Map<String,Object> paraMap =new HashMap<String,Object>();
//		String acct_id = CommonUtils.getMapKeyVal(paraMap, "acct_id");
//		String recharge_type = CommonUtils.getMapKeyVal(paraMap, "recharge_type");// 02 - 支付宝充值； 03 - 微信充值
//      String buyer_login_id = CommonUtils.getMapKeyVal(paraMap, "buyer_login_id");
//		String bank_type = CommonUtils.getMapKeyVal(paraMap, "bank_type");
//		String bank_name = CommonUtils.getMapKeyVal(paraMap, "bank_name");		
//		String tid = CommonUtils.getMapKeyVal(paraMap, "tid");
//		String app_id = CommonUtils.getMapKeyVal(paraMap, "app_id");
//		String out_trade_no = CommonUtils.getMapKeyVal(paraMap, "out_trade_no");
//		String amount = CommonUtils.getMapKeyVal(paraMap, "amount");//充值金额		
//		String time_end = CommonUtils.getMapKeyVal(paraMap, "time_end");//支付完成时间
//		String cust_id = CommonUtils.getMapKeyVal(paraMap, "cust_id");//客户ID
//		String userid = CommonUtils.getMapKeyVal(paraMap, "userid");
		
		String[] sid_gid = attach.split("\\|");
		String userid = sid_gid[0];
		String balance_pay_amount = sid_gid[1];
		
		Record userinofRd = Userinfo.dao.userInfo(userid);
		String station_id = String.valueOf(userinofRd.get("station_id"));
		//判断支付已记录
		PayLog plog = PayLog.me.findFirst("select 1 from pay_log where pay_no = '"+tid+"' and status = '00A' ");
		if(plog!=null){
			 renderText("success");
			 return;
		}
		//保存到支付记录
		PayLog paylog = new PayLog();
		paylog.set("user_id", userid);
		paylog.set("open_id", "");
		paylog.set("pay_no", tid);
		paylog.set("pay_method", "1");
		paylog.set("create_time",  DateUtil.getDateStr(time_end));
		paylog.set("amount", allamount);
		paylog.set("status", "00A");
		paylog.set("source_xml", notityXml);
		paylog.set("remark", "");
		paylog.set("out_trade_no", out_trade_no);
		paylog.save();
		
       	String sql=" SELECT r.cust_id,r.user_id,a.acct_id FROM orderinfo r,account a WHERE r.cust_id=a.cust_id and r.order_id='"+out_trade_no+"' ";
		Record orderrd = Db.findFirst(sql);
		//客户ID
		int cust_id = orderrd.getInt("cust_id");
		int acct_id = orderrd.getInt("acct_id");//账户ID
		paraMap.put("acct_id", String.valueOf(acct_id));
		paraMap.put("recharge_type", "03");
		paraMap.put("buyer_login_id", "");
		paraMap.put("bank_type", bank_type);
		paraMap.put("bank_name", "");
		paraMap.put("tid", tid);
		paraMap.put("app_id", WxConst.appid);
		paraMap.put("out_trade_no", out_trade_no);
		paraMap.put("amount", allamount);
		paraMap.put("time_end", time_end+"");
		paraMap.put("cust_id", String.valueOf(cust_id));
		paraMap.put("userid", userid);
		paraMap.put("station_id", station_id);
		
		//完成充值流程
		boolean rechargestatus = Account.dao.recharge(paraMap);
		
		//再进行扣款流程
		Map<String,Object> payMap =new HashMap<String,Object>();
		payMap.put("cust_id", String.valueOf(cust_id));
		payMap.put("online_amount", allamount);
		payMap.put("balance_pay_amount", balance_pay_amount);
		payMap.put("out_trade_no", out_trade_no);
		payMap.put("user_id", userid);
		boolean paystatus = Account.dao.pay(payMap);
		
		//判断平台内业务数据是否成功
		if(rechargestatus && paystatus){
			renderText("success");
		}else{
			renderText("fail");
		}
       } catch (Exception e) {
			 System.out.println("xml解析失败：" + e);
			 e.printStackTrace();
			 renderText("fail");
	   } 
	}
	
	/**
	 * 微信余额充值回调
	 * 支付结果
	 * */
	public void balancepayresult(){
		System.out.print("微信支付回调获取数据开始");
		HttpServletRequest request = getRequest();
		String inputLine;
		//String notityXml = "<xml><appid><![CDATA[wx7d9d3839bcf7a60b]]></appid><attach><![CDATA[1]]></attach><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[39500]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1397982802]]></mch_id><nonce_str><![CDATA[RfO38rYBIREtjlKUCeU1FqLBzqkmj3Jn]]></nonce_str><openid><![CDATA[ovbm3v1eeZAAcxyBgQAtGY7V1qkA]]></openid><out_trade_no><![CDATA[APP20161101123039594]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[7C2EB306C76A64F44B8F8E812244220D]]></sign><time_end><![CDATA[20161101073517]]></time_end><total_fee>39500</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[4002522001201609244763839121]]></transaction_id></xml>";

		String notityXml="";
		try {
			while ((inputLine = request.getReader().readLine()) != null) {
				notityXml += inputLine;
			}
			request.getReader().close();
		} catch (Exception e) {
			System.out.println("xml获取失败：" + e);
		}
		
		System.out.println("接收到的报文：" + notityXml);
		// 开始解析报文
        Map<String,Object> map = null;
       try {
	       	map =XMLUtil.doXMLParse(notityXml);
	       	//transaction_id 微信支付订单号
	      	String tid = CommonUtils.getMapKeyVal(map, "transaction_id");
	       	//out_trade_no商户订单号
	       	String out_trade_no =CommonUtils.getMapKeyVal(map, "out_trade_no");
	       	//attach  商家数据包 客户端自定义
	    	String attach =CommonUtils.getMapKeyVal(map, "attach");

	       	//现金支付金额订单现金支付金额，详见
			String amount = CommonUtils.getMapKeyVal(map, "cash_fee");
			/**把分转换成元**/
			String allamount = AmountUtils.changeF2Y(amount);
			
			//time_end 支付完成时间
			String time_end = CommonUtils.getMapKeyVal(map, "time_end");
			//付款银行
			String bank_type = CommonUtils.getMapKeyVal(map, "bank_type");
			
			
			//判断支付已记录
			PayLog plog = PayLog.me.findFirst("select 1 from pay_log where pay_no = '"+tid+"' and status = '00A' ");
			if (plog != null) {
				renderText("success");
				return;
			}
			
			/******
			 * wsh
			 * 16.11.02
			 * 通过out_trade_no查询虚拟订单
			 */
			VirtualOrder order = VirtualOrder.dao.findById(out_trade_no);
			order.set("status", "PAID");//虚拟订单修改成已支付
			order.update();
			//客户ID
			String cust_id = String.valueOf(order.getInt("cust_id"));
			//账户ID
			String acct_id = String.valueOf(order.getInt("acct_id"));
			//用户ID
			String user_id = String.valueOf(order.getInt("user_id"));
			
			Record userinofRd = Userinfo.dao.userInfo(user_id);
			String station_id = String.valueOf(userinofRd.get("station_id"));
			
			//保存到支付记录
			PayLog paylog = new PayLog();
			paylog.set("user_id", user_id);
			paylog.set("open_id", "");
			paylog.set("pay_no", tid);
			paylog.set("pay_method", "1");
			paylog.set("create_time",  DateUtil.getDateStr(time_end));
			paylog.set("amount", allamount);
			paylog.set("status", "00A");
			paylog.set("source_xml", notityXml);
			paylog.set("remark", "");
			paylog.set("out_trade_no", out_trade_no);
			paylog.save();
			
			//先完成充值流程
			Map<String,Object> paraMap =new HashMap<String,Object>();
			paraMap.put("acct_id", acct_id);
			paraMap.put("recharge_type", "03");
			paraMap.put("buyer_login_id", "");
			paraMap.put("bank_type", bank_type);
			paraMap.put("bank_name", "");
			paraMap.put("tid", tid);
			paraMap.put("app_id", WxConst.appid);
			paraMap.put("out_trade_no", out_trade_no);
			paraMap.put("amount", allamount);
			paraMap.put("time_end", time_end+"");
			paraMap.put("cust_id", cust_id);
			paraMap.put("userid", user_id);
			paraMap.put("station_id", station_id);
			
			//完成充值流程
			boolean rechargestatus = Account.dao.balancerecharge(paraMap);
			//判断平台内业务数据是否成功
			if(rechargestatus){
				renderText("success");
			}else{
				renderText("fail");
			}
			
       } catch (Exception e) {
			 System.out.println("xml解析失败：" + e);
			 e.printStackTrace();
			 renderText("fail");
	   }
	}
}
